'use strict';

stareal
    .controller("FreeTicketController", function ($scope, $api, $stateParams, $state, $lazyLoader,$window,$alert,$interval,localStorageService,$timeout,$http) {
        $scope.telphone_no = "";
        $scope.paracont = "获取验证码";
        $scope.code = "";
        $scope.sendCodeStatus=false;
        $scope.CertificateIcon=1;
        $scope.certificatenum='';
        $scope.myshowbtn=false;
        $scope.downloadShow=false;
        // $scope.downloadmystatus=false;
        $scope.riQi=1;
        // var ua = window.navigator.userAgent.toLowerCase();
        // if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        //     $scope.downloadShow=true;
        // }
        if($stateParams.freeTicketId==1){
            $scope.sumbitFreeTicket=true;
        }else{
            $scope.sumbitFreeTicket=false;
        }
        var h=(4.38*parseFloat(document.documentElement.style.fontSize)-120)/2+"px";
        $("#topHead_bg").height($(window).width()/1.13+'px');
        $("#footercontainer").height($(window).width()/3.11+'px');
        $(".FreeTickethead_box_qcorder_erwei").css('top',h);
        function validatemobile(mobile) {
            console.log(mobile);
            if (mobile.length == 0) {
                $alert.show('请输入手机号码！');
                return false;
            }
            if (mobile.length != 11) {
                $alert.show('请输入11位手机号码！');
                return false;
            }
            //  var myreg = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,2,3,5-9])|(17[0-9]))\d{8}$/;
            var myreg = /^1[3|4|5|6|7|8|9][0-9]{9}$/; //验证规则
            if (!myreg.test(mobile)) {
                $alert.show('请输入有效的手机号码！');
                return false;
            }
            return true;
        }
        function isCardNo(card) {
// 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
            // var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; //身份证
            // var reg=/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}(\d|x|X)$/;//身份证
            var reg = /^[0-9a-zA-Z]+$/;
            if(reg.test(card) === false) { //身份证
                $alert.show("请输入有效的,合法的身份证号！");
                return false;
            }
            if(card.length>25){
                $alert.show("请输入有效的,合法的身份证号！");
                return false;
            }
            return true;
        }
        function isCardTai(card){  //台胞证
            // var reg=/^([0-9]{8}|[0-9]{10})$/ ; //台胞证
            var reg = /^[0-9a-zA-Z]+$/;
            if(reg.test(card) === false) {
                $alert.show("请输入有效的,合法的台胞证号！");
                return false;
            }
            if(card.length>25){
                $alert.show("请输入有效的,合法的台胞证号！");
                return false;
            }
            return true;
        }
        function isCardHONG(card){  //港澳回乡证
            // var reg=/^([0-9]{8}|[0-9]{10})$/ ; //港澳回乡证
            var reg = /^[0-9a-zA-Z]+$/;
            if(reg.test(card) === false) {
                $alert.show("请输入有效的,合法的港澳居民回乡证号！");
                return false;
            }
            if(card.length>25){
                $alert.show("请输入有效的,合法的港澳居民回乡证号！");
                return false;
            }
            return true;
        }
        function isCardHONG2(card){  //港澳回乡证
            // var reg=/^([0-9]{8}|[0-9]{10})$/ ; //港澳回乡证
            var reg = /^[0-9a-zA-Z]+$/;
            if(reg.test(card) === false) {
                $alert.show("请输入有效的,合法的港澳居民居住证号！");
                return false;
            }
            if(card.length>25){
                $alert.show("请输入有效的,合法的港澳居民居住证号！");
                return false;
            }
            return true;
        }
        function isCardStudent(card){  //学生证
            // var reg=/^([0-9]{8}|[0-9]{10})$/ ; //学生证
            var reg = /^[0-9a-zA-Z]+$/;
            if(reg.test(card) === false) {
                $alert.show("请输入有效的学生证号！");
                return false;
            }
            if(card.length>25){
                $alert.show("请输入有效的学生证号！");
                return false;
            }
            return true;
        }
        var second = 60;
        var timerHandler = undefined;
        $scope.sendCode = function () {
            var  rs = "main.freeticket-" + JSON.stringify({freeTicketId:1});
            // var token=localStorageService.get('token');
            // var isbind = localStorageService.get('isbind');
            // var openID = localStorageService.get('openid');
            // if(isbind!=1&&openID!=''){
            //     localStorageService.set('cleartoken',token);
            //     location.href = "#/main/register/"+encodeURIComponent(rs);
            //     localStorageService.set('token','');
            //     return false
            // }
            if (!localStorageService.get('token')) {
                var  rs = "main.freeticket-" + JSON.stringify({freeTicketId:1});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        // "appid=wxd39f7e740343d507&" +
                        // "redirect_uri=http%3A%2F%2Fwww.mydeershow.com%2Foauth%2Findex" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs);
                } else {
                   location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
            if($scope.myName==undefined||$scope.myName==null||$scope.myName==''){
                $alert.show("姓名不能为空！");
                return;
            }else if($scope.myName.length<2){
                $alert.show("姓名不能少于2个字符！");
                return;
            }
            if (!validatemobile($scope.telphone_no)) {
                return;
            }

            if( $scope.sendCodeStatus){
                return;
            }
            // 演出分类
            $api.get("app/login/code/retrieve", {mobile: $scope.telphone_no, type: "0"})
                .then(function (ret) {
                    if (ret.retCode == "0") {
                        $alert.show("验证码已发送!");
                        timerHandler = $interval(function () {
                            if (second <= 0) {
                                $interval.cancel(timerHandler);
                                timerHandler = undefined;
                                second = 60;
                                $scope.paracont = "重发验证码";
                                $scope.sendCodeStatus=false;
                            } else {
                                $scope.sendCodeStatus=true;
                                $scope.paracont = second + "秒";
                                second--;
                            }
                        }, 1000, 100)
                        $scope.code_token=ret.accessToken;
                    } else {
                        $alert.show("验证码发送失败，请稍后重试!");
                    }
                },function(err){
                    $alert.show(err);
                });
        };
        $scope.switchIcon=function(index){
            $scope.CertificateIcon=index;
        }
        $scope.switchriQi=function(index){
            $scope.riQi=index;
        }
        $scope.submistFreeTicket=function(){ //app/ticket/freeticket
            if($("#myName").val()==''||$("#myName").val()==undefined||$("#myName").val()==null){
                $alert.show("姓名不能为空!");
                return;
            }
            if (!validatemobile($scope.telphone_no)) {
                return;
            }
            if($("#short_input").val()==''||$("#short_input").val()==undefined||$("#short_input").val()==null){
                $alert.show("短信验证码不能为空!");
                return;
            }
            if($("#Certificate_no").val()==''||$("#Certificate_no").val()==undefined||$("#Certificate_no").val()==null){
                $alert.show("证件号不能为空!");
                return;
            }
            if($scope.CertificateIcon==1){
                if(!isCardNo($scope.Certificate_no)){
                    return;
                }
            }else if($scope.CertificateIcon==2){
                if(!isCardTai($scope.Certificate_no)){
                    return;
                }
            }else if($scope.CertificateIcon==3){
                if(!isCardHONG($scope.Certificate_no)){
                    return;
                }
            }else if($scope.CertificateIcon==4){
                if(!isCardStudent($scope.Certificate_no)){
                    return;
                }
            }else if($scope.CertificateIcon==5){  //isCardHONG2
                if(!isCardHONG2($scope.Certificate_no)){
                    return;
                }
            }
            var field=''
            if($scope.riQi==1){
                field='13:00';
            }else if($scope.riQi==2){
                field='14:00';
            }else if($scope.riQi==3){
                field='15:00';
            }else if($scope.riQi==4){
                field='16:00';
            }
            $api.post("app/ticket/freeticket", { //CertificateIcon 1 省份证  //2台胞证
                name:$("#myName").val(),
                mobile:$scope.telphone_no,
                code:$("#short_input").val(),
                typeid:$scope.CertificateIcon,
                certificate:$("#Certificate_no").val(),
                field:field,
                token:$scope.code_token
            }).then(function (ret){
                //console.log(ret);
                $alert.show("回执码已发送，请输入注意查收回执码!");
                $scope.sumbitFreeTicket=false;
            },function(err){
                // console.log(ret);
                $alert.show(err) ;
                if(err=='你的手机号或者证件号已领过了！！'){
                    $scope.sumbitFreeTicket=false;
                }
            })
        }
        // $("#myqcorder").focus(function(){
        //
        // })

        //app/ticket/findById   回执码  生成二维码
        $scope.getErCode=function(){
            if($scope.myshowbtn){
                return;
            }
            if($("#myqcorder").val()==null||$("#myqcorder").val()==''||$("#myqcorder").val()==undefined){
                $alert.show("短信回执码不能为空!");
                return;
            }
            // if($("#myqcorder").val().length!=17){
            //     $alert.show("请输入正确的回执码!");
            //     return;
            // }

            $('html, body').animate({
                scrollTop: $("#FreeTickethead_box").offset().top
            });

            // $alert.show("正在生成电子票，请稍等!");
            $api.post("app/ticket/findById", { //CertificateIcon 1 省份证  //2台胞证
                message:$("#myqcorder").val()
            }).then(function (ret){
                console.log(ret);
                var data=ret.data;
                if(data.code!=undefined&&data.code!=null&&data.code!=''){
                    console.log($('#FreeTickethead_box_qcorder_erwei'));
                    $("#loadingCordedalog").show();
                    $('#FreeTickethead_box_qcorder_erwei').qrcode({
                        text:data.code
                    });
                    $scope.field='2018.10.13  '+data.field;
                    $scope.name=data.name;
                    $scope.certificatenum=data.certificate;
                    if($scope.certificatenum.length>12){
                        $scope.certificatenum0=$scope.certificatenum.slice(0,11);
                        $scope.certificatenum1=$scope.certificatenum.slice(11,$scope.certificatenum.length);
                    }else{
                        $scope.certificatenum0=$scope.certificatenum
                    }
                    $("#myqcorder").val('');

                    $timeout(function(){
                        //  $scope.downloadmystatus=true;
                        $scope.downloadShow = true;
                        $scope.myshowbtn = true;
                        mycut();
                        //html2Canvas();
                    },2000)
                }else{
                    $alert.show("电子票生成失败，请输入正确的回执码!");
                }
                // $scope.sumbitFreeTicket=false;
            },function(err){
                // console.log(ret);
                $alert.show(err) ;
            })
        }
        function convertBase64UrlToBlob(urlData) {
            var bytes = window.atob(urlData.split(',')[1]);
            //处理异常,将ascii码小于0的转换为大于0
            var ab = new ArrayBuffer(bytes.length);
            var ia = new Uint8Array(ab);

            for (var i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i);
            }
            return new Blob([ab], {type: 'image/png'});
        }
        function mycut(){
            var shareContent=document.getElementById('downImg');
            var width = $("#downImg").width();; //获取dom 宽度
            var height = $("#downImg").height(); //获取dom 高度
            var scale = 3; //定义任意放大倍数 支持小数
            var opts = {
                dpi:300,
                scale:scale,
                width:width,
                heigth:height,
                allowTaint: true,
                taintTest: false,
            };
            html2canvas(shareContent,opts).then(function(canvas) {
                //3. 图片导出为 png 格式
                var context = canvas.getContext('2d');
                // 【重要】关闭抗锯齿
                context.mozImageSmoothingEnabled = false;
                context.webkitImageSmoothingEnabled = false;
                context.msImageSmoothingEnabled = false;
                context.imageSmoothingEnabled = false;
                //console.log(canvas);
                var type = 'image/png';
                var imgData = canvas.toDataURL(type, 1);
                var _fixType = function (type) {
                    type = type.toLowerCase().replace(/jpg/i, 'jpeg');
                    var r = type.match(/png|jpeg|bmp|gif/)[0];
                    return 'image/' + r;
                };
                // 加工image data，替换mime type
                // var body = document.getElementsByTagName("body");
                // body[0].appendChild(canvas);
                //imgData = imgData.replace(_fixType(type), 'image/octet-stream');
                var str = '<img src="' +imgData + '" class="FreeTickethead_box_qcorderbg" id="creatImg">';
                $("#downImg").html(str);
                $timeout(function () {
                    $("#loadingCordedalog").hide();
                    var imgs = document.getElementById("creatImg");
                    imgs.addEventListener(triggerEvent, function () {
                        var url = this.getAttribute("src");
                        var ua = window.navigator.userAgent.toLowerCase();
                        if (/iphone/.test(ua)&&ua.match(/MicroMessenger/i) != 'micromessenger') {
                            saveAs(url);
                        }
                     //    var dtask = plus.downloader.createDownload(imgData, {}, function ( d, status ) {
                     //        // 下载完成
                     //        if ( status == 200 ) {
                     //            plus.gallery.save(picname,function() {
                     //                // /保存到相册方法
                     //                mui.toast('已保存到手机相册');
                     //            }, function() {				mui.toast('保存失败，请重试！');
                     //            });		} else {
                     //
                     //        }	});
                     //    dtask.addEventListener( "statechanged", onStateChanged, false );
                     //    dtask.start();//开始下载
                    }, false);




                }, 2000);
                //关闭裁剪框



            })
        }
        var triggerEvent = "touchstart"; //指定下载方式
        function saveAs(Url){

            var blob=new Blob([''], {type:'application/octet-stream'});

            var url = URL.createObjectURL(blob);

            var a = document.createElement('a');

            a.href = Url;

            a.download = Url.replace(/(.*\/)*([^.]+.*)/ig,"$2").split("?")[0];

            var e = document.createEvent('MouseEvents');

            e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

            a.dispatchEvent(e);

            //URL.revokeObjectURL(url);

        }





    });